package com.lp.mqtt.protocol;

import com.alibaba.fastjson.JSON;
import com.lp.bean.SimpleProtocolMqtt;
import com.lp.bo.IotNodeInfoBO;
import com.lp.bo.IotSensorInfoBO;
import com.lp.cache.CacheName;
import com.lp.cache.ProCacheUtil;
import com.lp.common.CodeIot;
import com.lp.mqtt.MqttService;
import com.lp.service.impl.IotNodeInfoServerImpl;
import com.lp.service.impl.IotSensorInfoServiceImpl;
import com.lp.util.ObjectUtil;
import com.lp.util.SpringApplicationContext;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ProtocalMing implements Iprotocal {

  @Override
  public void analysisData(String topic, byte[] data, String msg) {
    // 这边可以保证主题都是 /dev/coo/device_id
    msg = msg.replaceAll("\r|\n", "");

    // 交互的
    List<IotSensorInfoBO> list = new ArrayList<>();

    // 判断mqtt json 标识，兼容多种格式
    if (msg.contains("sid")) {
      List<SimpleProtocolMqtt> tmpList = JSON.parseArray(msg, SimpleProtocolMqtt.class);
      // 对象转换
      for (SimpleProtocolMqtt dt : tmpList) {
        IotSensorInfoBO tp = new IotSensorInfoBO();


        tp.setSensor_device_id(dt.getSid());
        tp.setPort_id(dt.getPid());
        tp.setSdata(dt.getDat());
        list.add(tp);
      }
    } else {
      list = JSON.parseArray(msg, IotSensorInfoBO.class);
    }

    String[] tmp = topic.split("/");
    String deviceCode = tmp[tmp.length - 1];

    IotNodeInfoBO nodeInfo = ProCacheUtil.getCache(CacheName.NODEINFO_DEVICECODE, deviceCode);

    if (ObjectUtil.isEmpty(nodeInfo)) {
      return;
    }

    if (nodeInfo.getIot_node_status() != CodeIot.DEVICE_STATUS.ONLINE) {
      IotNodeInfoBO nodB = new IotNodeInfoBO();
      nodB.setDevice_code(deviceCode);
      nodB.setIot_node_status(CodeIot.DEVICE_STATUS.ONLINE);
      IotNodeInfoServerImpl nodeTmp = SpringApplicationContext.getBeanType("iotNodeInfoServerImpl");
      nodeTmp.updateNodeStatus(nodB);
    }

    for (IotSensorInfoBO sensorInfo : list) {
      sensorInfo.setDevice_code(deviceCode);
      sensorInfo.setRequest_sdata(sensorInfo.getSdata());
      if (sensorInfo.getPort_id() == null) {
        sensorInfo.setPort_id(Integer.parseInt(sensorInfo.getSensor_device_id()));
      }
      if (ObjectUtil.isEmpty(sensorInfo.getMtime())) {
        sensorInfo.setMtime(new Date());
      }
      // 传感器处理
      IotSensorInfoServiceImpl app = (IotSensorInfoServiceImpl) SpringApplicationContext
          .getBean("iotSensorInfoServiceImpl");
      app.updateRealTimeData(sensorInfo);
    }

    // 下发通知消息
    IotNodeInfoBO iotNodeInfo = ProCacheUtil.getCache(CacheName.NODEINFO_DEVICECODE, deviceCode);

    // websocket 发送消息
    if (ObjectUtil.isNotEmpty(iotNodeInfo)) {
      String scene_id = ProCacheUtil.getCache(CacheName.SCENE_IPDATE_FLAG, "scene_" + iotNodeInfo.getScene_id());
      if (ObjectUtil.isNotEmpty(scene_id)) {
        MqttService.pubMessage("1", "/scene/update/" + iotNodeInfo.getScene_id());
      }
      String node_id = ProCacheUtil.getCache(CacheName.SCENE_IPDATE_FLAG, "node_" + iotNodeInfo.getId());
      if (ObjectUtil.isNotEmpty(node_id)) {
        MqttService.pubMessage("1", "/node/update/" + iotNodeInfo.getId());
      }
    }
  }

  @Override
  public void handbert(String topic) {
    // TODO Auto-generated method stub

  }

  @Override
  public void loginProtocal(Object obj) {
    // TODO Auto-generated method stub
    IotNodeInfoServerImpl tmp = SpringApplicationContext.getBeanType("iotNodeInfoServerImpl");
    tmp.updateNodeStatus(((IotNodeInfoBO) obj));
  }

  @Override
  public void logout(Object obj) {
    // TODO Auto-generated method stub
    IotNodeInfoServerImpl tmp = SpringApplicationContext.getBeanType("iotNodeInfoServerImpl");
    tmp.updateNodeStatus(((IotNodeInfoBO) obj));
  }

  @Override
  public Integer execServerControll(IotSensorInfoBO sensor, IotNodeInfoBO node) {
    if (node.getIot_node_status() == CodeIot.DEVICE_STATUS.ONLINE + 0) {
      MqttService.pubMessage("{\"sensor_device_id\":" + sensor.getSensor_device_id()
          + ",\"port_id\":" + sensor.getPort_id() + ",\"sdata\":" + sensor.getRequest_sdata() + "}",
          "/server/coo/" + node.getDevice_code());
      return 0;
    } else {
      return -1;
    }
  }

  @Override
  public Integer execServerParamWrite(IotSensorInfoBO sensor, IotNodeInfoBO node) {
    if (node.getIot_node_status() == CodeIot.DEVICE_STATUS.ONLINE + 0) {
      MqttService.pubMessage("{\"sensor_device_id\":" + sensor.getSensor_device_id()
          + ",\"port_id\":" + sensor.getPort_id() + ",\"sdata\":" + sensor.getRequest_sdata() + "}",
          "/server/coo/" + node.getDevice_code());
      return 0;
    } else {
      return -1;
    }
  }

  @Override
  public Integer execServerParamRead(IotSensorInfoBO sensorInfo, IotNodeInfoBO node) {
    if (node.getIot_node_status() == CodeIot.DEVICE_STATUS.ONLINE + 0) {
      MqttService.pubMessage("{\"sensor_device_id\":" + sensorInfo.getSensor_device_id()
          + ",\"port_id\":" + sensorInfo.getPort_id() + "}",
          "/server/coo/" + node.getDevice_code());
      return 0;
    } else {
      return -1;
    }
  }

}
